package com.haopt.clock.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.haopt.clock.dao.TIntegralMapper;
import com.haopt.clock.dao.TUserMapper;
import com.haopt.clock.dto.ResultDTO;
import com.haopt.clock.entity.TClockIn;
import com.haopt.clock.entity.TIntegral;
import com.haopt.clock.entity.TUser;
import com.haopt.clock.service.IntegralService;
import com.haopt.clock.utils.BeanHelper;
import com.haopt.clock.utils.DataUtil;
import com.haopt.clock.vo.ReqPageVO;
import com.haopt.clock.vo.ResInteralDetailVO;
import com.haopt.clock.vo.ResPageVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;

/**
 * @author haopt
 * @version 1.0
 * @ClassName IntegralServiceImpl
 * @Description TODO
 * @date 2021/3/22 13:36
 */
@Service
public class IntegralServiceImpl implements IntegralService {

    @Autowired
    private TIntegralMapper integralMapper;
    @Autowired
    private TUserMapper userMapper;
    @Override
    public ResultDTO<ResPageVO<ResInteralDetailVO>> listOfPage(ReqPageVO vo) {
        //分页获取积分榜列表
        PageHelper.startPage(vo.getCurrentPage(), vo.getPageSize());
        Example example = new Example(TIntegral.class);
        example.setOrderByClause("total_score desc");
        List<TIntegral> integralList = integralMapper.selectByExample(example);
        PageInfo<TIntegral> pageInfo = new PageInfo<>(integralList);
        //返回对象
        ResPageVO<ResInteralDetailVO> result = new ResPageVO<>();
        List<TIntegral> list = pageInfo.getList();
        List<ResInteralDetailVO> resList = new ArrayList<>();
        //封装返回数据
        if(!CollectionUtils.isEmpty(list)){
            list.forEach(bean->{
                ResInteralDetailVO resInteralDetailVO = BeanHelper.copyProperties(bean, ResInteralDetailVO.class);
                //获取用户信息
                TUser user = userMapper.selectByPrimaryKey(bean.getUserId());
                if(!DataUtil.isNullOrEmpty(user)){
                    resInteralDetailVO.setName(user.getName());
                    resInteralDetailVO.setUrl(user.getUrl());
                }
                resInteralDetailVO.setTotal(bean.getTotalScore());
                resList.add(resInteralDetailVO);
            });
        }
        //分页封装
        result.setCurrentPage(pageInfo.getPageNum());
        result.setList(resList);
        result.setPageSize(pageInfo.getSize());
        result.setTotal(pageInfo.getTotal());
        return ResultDTO.okOf(result);
    }
}
